package com.lianda.java8.functional.base.benchmark;

import java.lang.invoke.*;
import java.lang.reflect.Method;
import java.util.function.BiConsumer;

//构建lambda对象
//https://www.cnblogs.com/cubacn/p/cuba-reflection.html
public class LambdaCreator {

    public BiConsumer createVoidHandlerLambda(Object bean, Method method) throws Throwable {
        MethodHandles.Lookup caller = MethodHandles.lookup();
        String invokedName = "accept";
        //调用的函数式类的类型
        MethodType invokedType = MethodType.methodType(BiConsumer.class);

        //调用的形式方法的入参和出参，组成类型
        MethodType samMethodType = MethodType.methodType(void.class, Object.class, Object.class);

        MethodHandle implMethod = caller.findVirtual(bean.getClass(), method.getName(),
                MethodType.methodType(void.class, method.getParameterTypes()[0]));

        //实际调用的方法的入参和出参，组成类型
        MethodType instantiatedMethodType = MethodType.methodType(void.class, bean.getClass(),
                method.getParameterTypes()[0]);

        CallSite site = LambdaMetafactory.metafactory(
                caller, invokedName,
                invokedType,
                samMethodType,
                implMethod,
                instantiatedMethodType
        );

        MethodHandle factory = site.getTarget();
        BiConsumer listenerMethod = (BiConsumer) factory.invoke();

        return listenerMethod;
    }
}
